package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.utils.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * Created by yuanxin
 * Date:2019/7/7
 * Time:14:15
 */
@Controller
public class SearchController {
    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) throws Exception {
        //字符集处理
        searchMap = WebUtil.convertCharsetToUTF8(searchMap);
        //url处理
        StringBuffer url = new StringBuffer("/search.do?");
        for (String key : searchMap.keySet()) {
            url.append("&" + key + "=" + searchMap.get(key));
        }
        if (searchMap.get("pageNo") == null) {
            searchMap.put("pageNo","1");
            url.append("&pageNo=" + searchMap.get("pageNo"));
        }
        if (searchMap.get("sort") == null) {
            searchMap.put("sort","");
            url.append("&sort=" + searchMap.get("sort"));
        }
        if (searchMap.get("sortOrder") == null) {
            searchMap.put("sortOrder","DESC");
            url.append("&sortOrder=" + searchMap.get("sortOrder"));
        }
        Integer pageNo = Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        //远程调用接口
        Map result = skuSearchService.search(searchMap);

        //页码数量控制
        Integer totalPages = (Integer) result.get("totalPages");
        Integer startPage = 1;//开始页码
        Integer endPage = (totalPages==0)?1:totalPages;//截止页码
        if (totalPages > 5) {
            startPage = pageNo-2;
            if (startPage <= 0) {
                startPage = 1;
            }
            endPage = startPage+4;
            if (endPage > totalPages) {
                endPage=totalPages;
            }
        }

        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);
        model.addAttribute("result", result);
        model.addAttribute("url", url);
        model.addAttribute("searchMap",searchMap);
        return "search";
    }
}
